import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate"

Vue.use(Vuex)

// types
const types = {
  SET_LOCATION: 'SET_LOCATION',
  SET_ADDRESS: 'SET_ADDRESS'
}


// const state = {
//   location: {},
//   address: '',
// }
const state = {
  location:localStorage.getItem('Location')?localStorage.getItem('Location'):{},
  address:localStorage.getItem('Address')?localStorage.getItem('Address'):''
}

const getters = {
  location: state => state.location,
  address: state => state.address
}

const mutations = {
  [types.SET_LOCATION](state, location) {
    if (location) {
      state.location = location
    } else {
      state.location = null
    }
  },
  [types.SET_ADDRESS](state, address) {
    if (address) {
      state.address = address
    } else {
      state.address = null
    }
  },
}

const actions = {
  // context.commit
  setLocation: ({ commit }, location) => {
    commit(types.SET_LOCATION, location)
  },
  setAddress: ({ commit }, address) => {
    commit(types.SET_ADDRESS, address)
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  // 将state的数据全部存入localstorage
  // plugins: [createPersistedState({
  //   storage: window.sessionStorage,
  //   reducer(val) {
  //     return {
  //       location: val.location,
  //       address: val.address
  //     }
  //   }
  // })]
})
